package com.hdu.other.nestedRecursion;

import jdk.nashorn.internal.objects.annotations.Where;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class lc772 {

    static int where;

    /**
     * 返回 ： 自己负责的这一段，计算的结果
     * 返回之前，需要更新全局变量where，为了上游函数知道从哪里继续计算
     * @param s
     * @param i
     * @return
     */
    public static int f(char[] s, int i)
    {
        int cur = 0;
        List<Integer> numbers = new ArrayList<>();
        List<Character> ops = new ArrayList<>();
        while (i < s.length && s[i] != ')')
        {
            if (s[i] >= '0' && s[i] <= '9')
            {
                // meet number
                cur = cur * 10 + s[i++] - '0';
            }
            else if (s[i] != '(')
            {
                // meet char + - * /
                push(numbers, ops, cur, s[i++]);
                cur = 0;
            }
            else
            {
                // meet '('
                cur = f(s , i + 1);
                i = where + 1;
            }
        }
        push(numbers, ops, cur, '+');
        where = i;
        return compute(numbers, ops);
    }

    private static int compute(List<Integer> numbers, List<Character> ops) {
        int n = numbers.size();
        int ans = numbers.get(0);
        for (int i = 1; i < n; i++)
        {
            ans += ops.get(i - 1) == '+' ? numbers.get(i) : -numbers.get(i);
        }
        return ans;
    }

    static void push(List<Integer> numbers, List<Character> ops, int cur, char op)
    {
        int n = numbers.size();
        if (n == 0 || ops.get(n - 1) == '+' || ops.get(n - 1) == '-')
        {
            numbers.add(cur);
            ops.add(op);
        }
        else
        {
            int topNumber = numbers.get(n - 1);
            char topOp = ops.get(n - 1);
            if (topOp == '*')
            {
                numbers.set(n - 1, topNumber * cur);
            }
            else
            {
                numbers.set(n - 1, topNumber / cur);
            }
            ops.set(n - 1, op);
        }
    }
}
